package co.yixiang.util

import cn.hutool.core.bean.BeanUtil
import cn.hutool.core.date.DateUtil
import cn.hutool.core.util.IdUtil
import co.yixiang.api.ApiResult
import co.yixiang.business.post.UserInfo
import co.yixiang.modules.user.service.YxUserService
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
import kotlin.math.acos
import kotlin.math.cos
import kotlin.math.sin

data class ColumnModel(val type: String? = "varchar", val size: Int? = 100, val defaultValue: String? = "''", val desc: String? = "")

data class PageModel(var userId: Long? = null, var page: Int? = 1, var pageSize: Int? = 10)

//获取字段注释常量
fun getColumnString(columnModel: ColumnModel) = "${columnModel.type}(${columnModel.size}) default ${columnModel.defaultValue} column ${columnModel.desc}"

fun nextId() = IdUtil.createSnowflake(1,1).nextId().toString()

fun<T> T.getApiResult(status: Int?, message: String?): ApiResult<*> {

    return when (status) {
        200 -> {
            ApiResult.ok(this, message)
        }
        else -> {
            ApiResult.fail(status, message)
        }
    }
}

/**
 * 分页
 */
fun <T> List<T>.toPage(page: Int, pageSize: Int): List<T> = this.takeIf { it.isNotEmpty() }?.run {

    when {
        this.size < (page - 1)* pageSize -> emptyList()
        (page - 1)* pageSize < this.size && this.size < page * pageSize - 1 -> this.slice((page - 1)* pageSize until this.size)
        else -> this.slice((page - 1)* pageSize until page * pageSize)
    }
} ?: emptyList()

inline fun <T, R> MutableList<T>.toListVo(transform: (T) -> (R?)): MutableList<R> =  this.mapNotNull { transform(it) }.toMutableList()


data class Point2D( var longitude: Double? = 0.0, var latitude: Double? = 0.0)

// 平均半径,单位：m
const val EARTH_RADIUS: Double = 6371393.0
fun getDistance(pointA: Point2D, pointB: Point2D): Double {

    // 经纬度（角度）转弧度。弧度用作参数，以调用Math.cos和Math.sin
    // 经纬度（角度）转弧度。弧度用作参数，以调用Math.cos和Math.sin
    val radiansAX = Math.toRadians(pointA.longitude!!) // A经弧度

    val radiansAY = Math.toRadians(pointA.latitude!!) // A纬弧度

    val radiansBX = Math.toRadians(pointB.longitude!!) // B经弧度

    val radiansBY = Math.toRadians(pointB.latitude!!) // B纬弧度

    val cos = (cos(radiansAY) * cos(radiansBY) * cos(radiansAX - radiansBX)
            + sin(radiansAY) * sin(radiansBY))

    val acos = acos(cos) // 反余弦值

    return EARTH_RADIUS * acos // 最终结果
}

@Service
class UserServiceKT(@Autowired val yxUserService: YxUserService){

    /**
     * 获取用户信息
     */
    fun getUserInfo(userIdParam: Long): UserInfo? {

        return yxUserService.getById(userIdParam)?.let {
            UserInfo().apply {

                BeanUtil.copyProperties(it, this)
                userId = it.uid
                age = it.birthday
            }
        }
    }

}
